<template>
  <a-button type="outline" @click="handleClick">AI生成题目</a-button>
  <a-drawer
    :width="340"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    unmountOnClose
  >
    <template #title> AI生成题目</template>
    <div>
      <a-form
        :model="form"
        label-align="left"
        auto-label-width
        @submit="handleSubmit"
      >
        <a-form-item label="应用名称">
          {{ appId }}
        </a-form-item>
        <a-form-item field="questionNumber" label="题目数量">
          <a-input-number
            min="0"
            max="20"
            v-model="form.questionNumber"
            placeholder="请输入题目数量"
          />
        </a-form-item>
        <a-form-item field="optionNumber" label="选项数量">
          <a-input-number
            min="0"
            max="6"
            v-model="form.optionNumber"
            placeholder="请输入选项数量"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button
              :loading="submitting"
              type="primary"
              html-type="submit"
              style="width: 120px"
            >
              {{ submitting ? "生成中" : "一键生成" }}
            </a-button>
            <a-button
              type="primary"
              style="width: 120px"
              @click="handSSEleSubmit"
            >
              实时生成
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { defineProps, reactive, ref, watchEffect, withDefaults } from "vue";
import { useLoginUserStore } from "@/store/userStore";
import meassage from "@arco-design/web-vue/es/message";
import API from "@/api";
import { useRouter } from "vue-router";

import message from "@arco-design/web-vue/es/message";
import { aiGenerateQuestionUsingPost } from "@/api/questionController";

const loginUserStore = useLoginUserStore();
const router = useRouter();
const form = reactive({
  optionNumber: 2,
  questionNumber: 10,
} as API.AiGenerateQuestionRequest);

interface Props {
  appId: string;
  onSuccess?: (result: API.QuestionContenDto[]) => void;
  onSSESuccess?: (result: API.QuestionContenDto) => void;
  onSSEStart?: (event: any) => void;
  onSSEClose?: (event: any) => void;
}

const props = withDefaults(defineProps<Props>(), {
  appId: () => {
    return "";
  },
});

const visible = ref(false);
const submitting = ref(false);

const handleClick = () => {
  visible.value = true;
};
const handleOk = () => {
  visible.value = false;
};
const handleCancel = () => {
  visible.value = false;
};

const handleSubmit = async () => {
  if (!props.appId) {
    return;
  }
  submitting.value = true;

  const res = await aiGenerateQuestionUsingPost({
    appId: props.appId as any,
    ...form,
  });
  if (res.data.code == 0 && res.data.data.length > 0) {
    if (props.onSuccess) {
      props.onSuccess(res.data.data);
    } else {
      message.success("生成成功");
    }
    //关闭抽屉
    handleCancel();
  } else {
    message.error("生成失败");
  }
  submitting.value = false;
};
/**
 * 提交(实时返回)
 */
const handSSEleSubmit = async () => {
  if (!props.appId) {
    return;
  }
  //创建SSE请求
  const eventSource = new EventSource(
    //todo 手动填写完整的后端请求
    `http://localhost:8101/api/question/ai_generate/sse?appId=${props.appId}&optionNumber=${form.optionNumber}&questionNumber=${form.questionNumber}`
  );
  let first = true;
  //接受消息
  eventSource.onmessage = function (event) {
    if (first) {
      props.onSSEStart?.(event);
      handleCancel();
      first = !first;
    }
    props.onSSESuccess?.(JSON.parse(event.data));
  };
  // 连接关闭时触发
  eventSource.onerror = function (event) {
    if (event.eventPhase == EventSource.CLOSED) {
      console.log("连接关闭");
      eventSource.close();
      props.onSSEClose?.(event);
    }
  };
  // // 连接打开时触发
  // eventSource.onopen = function (event) {
  //   console.log("建立链接");
  //   props.onSSEStart?.(event);
  //   handleCancel();
  // };
};
</script>
